from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.utils.timesince import timesince

from accounts.models import *
from accounts.fields import *

class NewAccountForm(forms.ModelForm):
    """
    Creates a new Account, auth.User (auth_owner), Site, and AccountUser (from owner).
    The fields are a bit more "friendly" -- minimal input is required, most of the
    real work is done behind the scenes.
    """
    class Meta:
        model = Account
        exclude = ('number', 'created', 'site', 'auth_owner', 'referrer_code', 'next_renewal', 'status')
        
    fieldsets = (
            ("Account info", {'fields': ('name', 'label', 'domain', 'plan', 'price_override',)}),
            ('Create account admin', {'fields': ('first_name', 'last_name', 'username', 'password', 'email')}),
            ('Options', {'fields': ('referrer', 'send_welcome_email')}),
        )

    name = forms.CharField(max_length=50)
    label = AccountLabelField(
        help_text=u'<strong style="background:#ffffcc;color:#cc0000;">This cannot be changed later.</strong><br />'
        'It\'s used to create the default subdomain.  The resulting domain name <strong>can</strong> be changed later.',
    )
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    plan = RatePlanField()
    username = UsernameField()
    password = forms.CharField(min_length=6, initial=User.objects.make_random_password)
    email = forms.EmailField()
    domain = forms.ChoiceField(choices=settings.ACCOUNT_SUBDOMAIN_CHOICES)
    send_welcome_email = forms.BooleanField(required=False)
    
    def save_m2m(self, *args, **kwargs):
        pass
    
    def save(self, commit=True):
        account = Account.objects.create_new_account(**self.cleaned_data)
        if self.cleaned_data['send_welcome_email']:
            account.owner.send_welcome_email()
        return account
        

class EditAccountForm(forms.ModelForm):
    class Meta:
        model = Account
        exclude = ('site', 'auth_owner',)
        
    fieldsets = (
        ("Account info", {'fields': ('number', 'name', 'revenue', 'status', 'domain', 'label', 'created', 'how_heard', 'plan', 'price_override', 'next_renewal')}),
        ("Affiliate info", {'fields': ('referrer_code', 'referrer'), 'classes': ['collapse']}),
    )
    
    name = forms.CharField(max_length=50)
    label = forms.CharField()
    domain = forms.CharField(max_length=100)
    plan = RatePlanField()
    revenue = forms.CharField(max_length=100)
    
    def __init__(self, *args, **kwargs):
        super(EditAccountForm, self).__init__(*args, **kwargs)
        account = kwargs['instance']
        self.fields['number'].widget = ReadOnlyWidget(account.number, account.number)
        self.fields['label'].widget = ReadOnlyWidget(account.label, account.label)
        self.fields['referrer_code'].widget = ReadOnlyWidget(account.referrer_code, account.referrer_code)
        self.fields['how_heard'].widget = ReadOnlyWidget(account.how_heard, account.get_how_heard_display())
        self.fields['how_heard'].label = 'How did you hear about us?'
        self.fields['referrer'].widget = ReadOnlyWidget(account.referrer, account.referrer)
        self.fields['created'].widget = ReadOnlyWidget(account.created, "%s <br /><strong>(%s ago)</strong>" % (account.created.strftime("%B %d, %Y at %H:%M"), timesince(self.instance.created)))
        self.fields['name'].initial = account.site.name
        self.fields['domain'].initial = account.site.domain
        self.fields['plan'].initial = account.subscription.plan.id
        self.fields['revenue'].widget = ReadOnlyWidget(account.revenue, account.revenue)
        self.original_plan = account.subscription.plan
    
    def clean_label(self):
        # Not rendering an <input> isn't enough to ensure the label doesn't get changed. 
        return self.instance.label
    
    def clean_domain(self):
        try:
            Site.objects.exclude(id=self.instance.site.id).get(domain__iexact=self.cleaned_data['domain'])
            raise forms.ValidationError("That domain is already taken.  Choose another.")
        except Site.DoesNotExist:
            return self.cleaned_data['domain']
    
    def save(self, *args, **kwargs):
        self.instance.site.name = self.cleaned_data['name']
        self.instance.site.domain = self.cleaned_data['domain']
        self.instance.site.save()
        if self.cleaned_data['plan'] != self.original_plan:
            self.instance.subscriptions.create(plan=self.cleaned_data['plan'])
        return super(EditAccountForm, self).save(*args, **kwargs)
